package com.oocl.server.runnable;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Map.Entry;

import org.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.qq.protocol.Action;
import com.oocl.qq.protocol.Protocol;
import com.oocl.server.analyzer.ProtocolAnalyzer;
import com.oocl.server.analyzer.impl.ProtocolAnalyzerImpl;
import com.oocl.server.util.JacksonUtil;
import com.oocl.server.util.Logger;

public class ChatRunnable extends Thread {
	
	private Socket socket;
	private ProtocolAnalyzerImpl analyzer;
	private InputStream in;
	private OutputStream out;
	private ObjectInputStream objectIn;
	private ObjectOutputStream objectOut;
	private Map<String, ChatRunnable> threadMap;
	private ObjectMapper mapper = new ObjectMapper();
	
	public ChatRunnable(Socket socket ,Map<String, ChatRunnable> threadMap){
		this.socket = socket;
		this.threadMap = threadMap;
		this.analyzer = new ProtocolAnalyzerImpl(threadMap,this);
		Logger.log("RequestThread初始化完成");
	}
	
	@Override
	public void run() {
		try{
			in = this.socket.getInputStream();
			out = this.socket.getOutputStream();
			objectOut = new ObjectOutputStream(out);
			objectIn = new ObjectInputStream(in);
			///收到request
			String recMsg = null;
			Protocol p;
			while(true){
				try {
					///分析
					recMsg = (String) objectIn.readObject();

	                p = JacksonUtil.fromJsonToObject(recMsg , Protocol.class);
					
					this.analyzer.analyze(p);
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}

		}catch(IOException e){
			/// 删除用户socket信息
			///并通知其他用户，更新在线用户列表
			this.analyzer.dealWithLogout();
			Logger.log("RequestThread中捕获的异常A");
//			e.printStackTrace();
		}
	}
	

	public void sendMsg(Protocol p){
		try {
			JSONObject jobj = new JSONObject();
			jobj.put("action", p.getAction());
			jobj.put("from", p.getFrom());
			jobj.put("to", p.getTo());
			jobj.put("msg", p.getMsg());
			jobj.put("time", p.getTime());
			objectOut.writeObject(jobj.toString());
			
			objectOut.writeObject(null);
		} catch (IOException e) {
			Logger.log("RequestThread中捕获的异常B");
			e.printStackTrace();
		}
		
	}
}
